package com.project.poetry.service.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.poetry.common.constant.ConstantValue;
import com.project.poetry.common.util.CommonUtil;
import com.project.poetry.service.entity.dto.code.CodeDTO;
import com.project.poetry.service.entity.po.code.CodePO;
import com.project.poetry.service.mapper.CodeMapper;
import com.project.poetry.service.service.CodeService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 字典业务层实现类
 * @author mengxj
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CodeServiceImpl extends ServiceImpl<CodeMapper, CodePO> implements CodeService {

    @Resource
    private CodeMapper codeMapper;

    @Override
    public List<CodeDTO> getCodesByType(Integer type) {
        List<CodePO> list = this.codeMapper.selectList(new QueryWrapper<CodePO>().lambda().eq(CodePO :: getType, type));
        return list.stream().map(po -> {
            CodeDTO dto = new CodeDTO();
            BeanUtils.copyProperties(po, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public String getValueByCode(Integer code) {
        if(Objects.isNull(code) || code.equals(-1)){
            return StrUtil.EMPTY;
        }
        CodePO po = this.codeMapper.selectOne(new QueryWrapper<CodePO>().lambda().eq(CodePO :: getCode, code));
        CommonUtil.checkThrow(Objects::isNull, po, ConstantValue.SERVICE_DATA_ERROR_STATUS_CODE, "字典代码传入错误！！！");
        return po.getValue();
    }
}
